const { exec } = require('child_process');
const os = require('os');

function killPort(port) {
  const platform = os.platform();
  let cmd, pidParser;

  if (platform === 'win32') {
    // Windows 命令
    cmd = `netstat -ano | findstr :${port}`;
    pidParser = (output) => {
      const lines = output.split('\n').filter(line => line.includes(`:${port}`));
      if (lines.length === 0) return null;
      const matches = lines[0].trim().split(/\s+/);
      return matches[matches.length - 1];
    };
  } else {
    // Linux/macOS 命令
    cmd = `lsof -i :${port} -t`;
    pidParser = (output) => output.split('\n')[0].trim();
  }

  return new Promise((resolve, reject) => {

    // 执行命令查找 PID
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(`端口 ${port} 未被占用`);
        resolve()
        return;
      }
  
      const pid = pidParser(stdout.toString());
      if (!pid) {
        console.log(`未找到占用端口 ${port} 的进程`);
        resolve()
        return;
      }
  
      // 终止进程
      console.log(platform);
      console.log(pid);
      const killCmd = platform === 'win32' 
        ? `taskkill /F /PID ${pid}`
        : `kill -9 ${pid}`;
  
      exec(killCmd, (killErr) => {
        if (killErr) {
          console.error(`终止进程失败 (PID: ${pid}):`, killErr.message);
          if (killErr.message.includes('权限')) {
            console.log('请尝试以管理员/root权限运行此脚本');
          }
          return;
        }
        console.log(`成功终止占用端口 ${port} 的进程 (PID: ${pid})`);
        resolve()
      });
    });
  })

}

exports.killPort = killPort
